import os

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.db import djangoforms

import django
from django import http
from django import shortcuts

from sendemail.models import *
from sendemail.helper import *
from sendemail.sessions import *
from sendemail.rotmodel import *
from settings import *
 
def list(request,id_company=None):
  params = {}
  configs = Config.all()
  
  p = int(SafeGet('page',0,request))+1
    
  StringPaging = paging(configs.count(),'?page=',PAGE_SIZE,p)
  
  configs = configs.fetch(PAGE_SIZE,((p-1)*PAGE_SIZE))
  
  params['Title'] = 'List Configs'
  params['list'] = configs
  params['StringPaging'] = StringPaging

  return respond(request, None, 'config_list', params)

def delete(request, idConfig):
  config = None
  if idConfig:
    config = Config.get_by_id(int(idConfig))
    if config is None:
      return respond(request, None, 'message_box', {"message":"No Config"})
  config.delete()
  return http.HttpResponseRedirect('/admin/config')     

def edit(request, idConfig):
  params = {}
  params['Title'] = 'Create or Edit Config'
  
  config = None
  if idConfig:
    config = Config.get_by_id(int(idConfig))
    if config is None:
      return respond(request, None, 'message_box', {"message":"No Config"})
  params['config'] = config
  
  if not request.POST:
      return respond(request, None, 'config_edit', params)
  
  if config is None:
      config = Config()
  
  try:            
      config.name  = request.POST.get('name')
      config.value   = request.POST.get('value')
  except db.Error, err:
      params['err'] = err
      params['config'] = config
      return respond(request, None, 'config_edit', params)
  
  key = config.put()

  return http.HttpResponseRedirect('/config')

def add(request):
  """Create a config.  GET shows a blank form, POST processes it."""
  return edit(request, None)
